﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using DuJianliang.ApplicationPlatform.Common;

namespace DuJianliang.ApplicationPlatform.UserPermission
{
    public partial class UserList : System.Web.UI.Page
    {
        UserPermissionBll userPermissionBll = new UserPermissionBll();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                UserPermissionBll userPermissionBll = new UserPermissionBll();
                if (!userPermissionBll.HasPermission(CurrentInfo.Instance.CurrentUser.ID, (int)Permission.UserManager))
                {
                    Response.Write("您没有权限使用该功能");
                    Response.End();
                    return;
                }
                BindGridView();
            }
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            Response.Redirect("UserEdit.aspx");
        }

        private void BindGridView()
        {
            string sql = @"SELECT * FROM dbo.t5715_User Order By TrueName";

            Database database = DatabaseFactory.CreateDatabase();
            DbCommand dbCommand = database.GetSqlStringCommand(sql);
            DataTable dataTable = database.ExecuteDataSet(dbCommand).Tables[0];

            gridView.DataSource = dataTable;
            gridView.DataBind();
        }

        private void Delete(string id)
        {
            string sql_delete = @"DELETE FROM  dbo.t5715_User WHERE UserID = @ID";

            try
            {
                if (userPermissionBll.IsAdmin(id) && !userPermissionBll.hasOtherAdmin(id))
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('这是系统中最后一个管理员，不能删除。');</script>"); 
                    return;
                }

                if (isUsed(id))
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('该用户已被使用，不允许删除。');</script>"); 
                }
                else
                {
                    Database database = DatabaseFactory.CreateDatabase();
                    DbCommand dbCommand = database.GetSqlStringCommand(sql_delete);
                    database.AddInParameter(dbCommand, "@ID", DbType.String, id);
                    database.ExecuteNonQuery(dbCommand);
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void gridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(e.CommandName) || e.CommandName.ToLower().Equals("page"))
            {
                return;
            }

            GridViewRow gridViewRow = ((GridViewRow)(((Button)(e.CommandSource)).Parent.Parent));            
            string id = gridView.DataKeys[gridViewRow.RowIndex]["UserID"].ToString();

            switch (e.CommandName)
            {
                case "CmdEdit":
                    Response.Redirect(string.Format("UserEdit.aspx?ID={0}", id));
                    break;
                case "CmdDelete":
                    this.Delete(id);
                    BindGridView();
                    break;
                case "CmdSetPermission" :
                    Response.Redirect(string.Format("SetUserPermission.aspx?userid={0}", id));
                    break;
                default:
                    break;
            }
        }

        protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridView.PageIndex = e.NewPageIndex;
            BindGridView();
        }

        private bool isUsed(string id)
        {
            //string sql_select = @"SELECT COUNT(ID) FROM dbo.FlowStepOperator WHERE OperatorInfo = @ID";

            //try
            //{
            //    Database database = DatabaseFactory.CreateDatabase();
            //    DbCommand dbCommand = database.GetSqlStringCommand(sql_select);
            //    database.AddInParameter(dbCommand, "@ID", DbType.String, id);
            //    string count = database.ExecuteScalar(dbCommand).ToString();
            //    return !count.Equals("0");
            //}
            //catch (Exception ex)
            //{
            //    throw ex;
            //}

            return false;
        }

        protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType != DataControlRowType.DataRow)
                return;

            string id = gridView.DataKeys[e.Row.RowIndex]["UserID"].ToString();

            TableCell tableCell_Dept = e.Row.Cells[3];
            DeptOB deptOB = userPermissionBll.GetDeptByUserID(id);
            tableCell_Dept.Text = deptOB.DeptFullName;

            TableCell tableCell_IsAdmin = e.Row.Cells[4];
            switch (tableCell_IsAdmin.Text.ToLower())
            {
                case "true":
                    tableCell_IsAdmin.Text = "是";
                    Button btnEdit = e.Row.FindControl("btnEdit") as Button;
                    if (btnEdit != null)
                    {
                        btnEdit.Enabled = false;
                    }
                    Button btnSetPermission = e.Row.FindControl("btnSetPermission") as Button;
                    if (btnSetPermission != null)
                    {
                        btnSetPermission.Enabled = false;
                    }
                    break;
                default:
                    tableCell_IsAdmin.Text = "否";
                    break;
            }            
        }
    }
}